package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.constant.MongoDbConstant;
import com.bbzn.device.client.dataobject.BatteryHis;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.SimpleMongoService;
import com.bbzn.device.client.utils.OptionalBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author wulongbo
 * @Date 2021/12/2 14:59
 * @Version 1.0
 */

@Component
public class EmqBatteryStrategy implements EmqStrategy {

    @Autowired
    private SimpleMongoService simpleMongoService;

    @Autowired
    private DeviceService deviceService;

    // 手表电量信息
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            Integer battery = jsonObject.getInteger("battery");
            if (!OptionalBean.ofNullable(battery).isPresent()) {
                return "json解析错误";
            }
            BatteryHis batteryHis = new BatteryHis();
            batteryHis.setImei(imei);
            batteryHis.setBattery(battery);
            batteryHis.setCreateTime(System.currentTimeMillis());
            batteryHis.setCreatedBy("emq");
            simpleMongoService.insert(batteryHis, MongoDbConstant.BATTERY_HIS);

            Device device = new Device();
            device.setImei(imei);
            device.setBattery(battery);
            deviceService.updateByImeiSelective(device);
        } catch (Exception e) {
            return "获取电量失败！";
        }
        return "获取电量成功！";
    }
}
